package ecom.appcode.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ecom.appcode.business.CategoryLogic;
import ecom.appcode.business.CategoryLogicImpl;
import ecom.appcode.business.OrderDetailLogic;
import ecom.appcode.business.OrderDetailLogicImpl;
import ecom.appcode.business.OrderLogic;
import ecom.appcode.business.OrderLogicImpl;
import ecom.appcode.business.ShoesLogic;
import ecom.appcode.business.ShoesLogicImpl;
import ecom.appcode.business.SizeLogic;
import ecom.appcode.business.SizeLogicImpl;
import ecom.appcode.business.UsersLogic;
import ecom.appcode.business.UsersLogicImpl;
import ecom.appcode.common.bean.ShoesBean;
import ecom.appcode.common.constants.CommonConstants;
import ecom.appcode.common.daobean.CartDaoBean;
import ecom.appcode.common.daobean.CategoryDaoBean;
import ecom.appcode.common.daobean.OrderDaoBean;
import ecom.appcode.common.daobean.ShoesDaoBean;
import ecom.appcode.common.daobean.UsersDaoBean;

/**
 * Servlet implementation class CartAction
 */
public class CartAction extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartAction() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String action = request.getParameter("btAction");
        if ("AddToCart".equals(action)) {
            String page = request.getParameter("txtPage");
            String string_categoryID = request.getParameter(CommonConstants.VALUE_CATEGORY_ID);
            int categoryID = 0;
            /** Load New Arrivals Copy */
            ShoesLogic shoesLogic = new ShoesLogicImpl();
            String categoryName = request.getParameter(CommonConstants.VALUE_CATEGORY_NAME);
            if ("mens.jsp".equals(page) || "new.jsp".equals(page)) {
                if (string_categoryID != null) {
                    categoryID = Integer.parseInt(string_categoryID);

                    if (categoryName == null || CommonConstants.BLANK.equals(categoryName)) {
                        CategoryLogic cateLogic = new CategoryLogicImpl();
                        CategoryDaoBean cateBean = cateLogic.loadCategoryByID(categoryID);
                        categoryName = cateBean.getCategoryName();
                    }

                    List<ShoesDaoBean> shoesList = shoesLogic.loadShoesbyCategoryID(categoryID);

                    if (shoesList != null) {
                        HttpSession session = request.getSession();
                        session.setAttribute(CommonConstants.SESSION_SHOES_CATEGORY, shoesList);
                        request.setAttribute(CommonConstants.REQUEST_CATEGORY_NAME, categoryName);
                    }
                }
            } else {
                // Load Sale Item
                List<ShoesDaoBean> shoesList = shoesLogic.loadAllSaleItems();

                if (shoesList != null) {
                    HttpSession session = request.getSession();
                    session.setAttribute(CommonConstants.SESSION_SHOES_CATEGORY, shoesList);
                }
            }

            int shoesID = Integer.parseInt(request.getParameter("txtShoesID"));

            ShoesDaoBean shoes = shoesLogic.loadAShoesProduct(shoesID);

            String string_realPrice = request.getParameter("txtRealPrice");
            float realPrice = 0;
            if (string_realPrice == null || CommonConstants.BLANK.equals(string_realPrice)) {
                realPrice = shoes.getUnitPrice();
            } else {
                realPrice = Float.parseFloat(string_realPrice);
            }

            ShoesBean shoesBean = new ShoesBean(shoes.getUrlImage(), shoes.getShoesID(), shoes.getShoesName(),
                    shoes.getBrand(), 1, realPrice);
            request.setAttribute(CommonConstants.REQUEST_CATEGORY_NAME, categoryName);
            HttpSession session = request.getSession(true);
            CartDaoBean cart = (CartDaoBean) session.getAttribute("SHOP");
            if (cart == null) {
                cart = new CartDaoBean();
            }
            cart.addShoes(shoesBean);
            session.setAttribute("SHOP", cart);
            RequestDispatcher rd = request.getRequestDispatcher(page);
            rd.forward(request, response);
        } else if ("Remove".equals(action)) {
            int shoesID = Integer.parseInt(request.getParameter("txtShoesID"));

            HttpSession session = request.getSession();
            if (session != null) {
                CartDaoBean shop = (CartDaoBean) session.getAttribute("SHOP");
                if (shop != null) {
                    shop.removeShoes(shoesID);
                    session.setAttribute("SHOP", shop);
                    RequestDispatcher rd = request.getRequestDispatcher("view-cart.jsp");
                    rd.forward(request, response);
                }
            }
        } else if ("Update".equals(action)) {
            int quantity = Integer.parseInt(request.getParameter("txtQuantity"));
            int shoesID = Integer.parseInt(request.getParameter("txtShoesID"));

            HttpSession session = request.getSession();
            if (session != null) {
                CartDaoBean shop = (CartDaoBean) session.getAttribute("SHOP");
                if (shop != null) {
                    shop.updateShoes(shoesID, quantity);
                    session.setAttribute("SHOP", shop);
                    RequestDispatcher rd = request.getRequestDispatcher("view-cart.jsp");
                    rd.forward(request, response);
                }
            }
        } else if ("CheckOut".equals(action)) {

            HttpSession session = request.getSession();
            String email = request.getParameter("txtEmail");

            System.out.println(email + " CCCCCCCCCCCCCCCCCCCCCCCC");
            if (session != null) {

                if (email == null || CommonConstants.BLANK.equals(email)) {
                    RequestDispatcher rd = request.getRequestDispatcher("checkout-ex.jsp");
                    rd.forward(request, response);
                } else {

                    UsersLogic userLogic = new UsersLogicImpl();
                    UsersDaoBean user = userLogic.loadUsersByEmail(email);
                    session.setAttribute("USER", user);

                    RequestDispatcher rd = request.getRequestDispatcher("confirm-checkout.jsp");
                    rd.forward(request, response);

                }
            }
        } else if ("Continue Shopping".equals(action)) {
            RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
            rd.forward(request, response);
        } else if ("Update Cart".equals(action)) {
            RequestDispatcher rd = request.getRequestDispatcher("view-cart.jsp");
            rd.forward(request, response);
        } else if ("Finish Purchase".equals(action)) {
            String email = request.getParameter("txtEmail");

            HttpSession session = request.getSession();
            SizeLogic size = new SizeLogicImpl();

            int num1 = size.rdInt(1, 100);
            int num2 = size.rdInt(50, 200);
            int num3 = size.rdInt(150, 300);

            int orderID = num1 * num3 + num2;

            // GET ONLINE DATE
            Date todayD = new Date(System.currentTimeMillis());
            SimpleDateFormat dayFormat = new SimpleDateFormat("MM/dd/yyyy");
            String today = dayFormat.format(todayD.getTime());

            OrderLogic orderLogic = new OrderLogicImpl();
            OrderDetailLogic orderDetailLogic = new OrderDetailLogicImpl();

            OrderDaoBean insertOrderShoes = orderLogic.insertOrderShoes(orderID, today, email, CommonConstants.BLANK,
                    false, 1, CommonConstants.BLANK, CommonConstants.BLANK);
            boolean resultOrderDetai = false;
            CartDaoBean shop = (CartDaoBean) session.getAttribute("SHOP");
            for (int i = 0; i < shop.getTotalList().size(); i++) {
                int shoesID = shop.getTotalList().get(i).getShoesID();
                int quantity = shop.getTotalList().get(i).getQuantity();
                float unitPrice = shop.getTotalList().get(i).getUnitPrice();
                float total = quantity * unitPrice;
                resultOrderDetai = orderDetailLogic.insertOrderDetails(shoesID, quantity, unitPrice, total, orderID);
            }
            if (resultOrderDetai) {
                session.setAttribute("SHOP", null);
                RequestDispatcher rd = request.getRequestDispatcher("order-successful.jsp");
                rd.forward(request, response);
            }

        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub

        String action = request.getParameter("btAction");
        if ("CheckOut".equals(action)) {
            OrderLogic orderLogic = new OrderLogicImpl();
            OrderDetailLogic orderDetailLogic = new OrderDetailLogicImpl();
            boolean resultOrder = orderLogic.insertOrder("1/1/2013", "tuantqse60604@gmail.com", "2/2/2013", true, 1,
                    "1/1/2012", "TEST");
            boolean resultOrderDetail = orderDetailLogic.insertOrderDetails(35, 2, 3, 50, 2);
        }

    }

}
